<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRole } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ArrowDown, Checked } from "@element-plus/icons-vue";
import { exchange_taskDetail } from "@/api/redemption";
import { customerData_taskDetail } from "@/api/outbound";
import { customer_insea_progress } from "@/api/customer"

import CustomerDetail from "./form/customerDetail.vue";
import Redemption from "./form/redemption.vue";
import SelfImport from "./form/selfImport.vue";

import Eye from "~icons/ri/Eye-line";
import Refresh from "~icons/ep/refresh";
import Checkbox from "~icons/ri/checkbox-fill";
import DeleteBin from "~icons/meteor-icons/trash-can";
import ABProgress from "@/components/ABProgress/index.vue";
import { Filter } from "@element-plus/icons-vue";
import { message } from "@/utils/message";
defineOptions({
  name: "CustomerDataMaterialPool"
});

const formRef = ref();
const detailRef = ref();
const redemptionRef = ref();
const selfImportRef = ref();
const {
  permissions,

  shortcuts,
  labelList,
  sourceList,
  form,
  loading,
  columns,
  dataList,
  pagination,
  tableRef,
  multipleSelection,

  handleCommand,
  conditionsOutboundClick,
  conditionsDiscardClick,
  conditionsAllocateClick,
  discardClick,
  transferHighseasClick,
  getLabelList,

  onSearch,
  resetForm,
  lookCustomer,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleSelectionClear
} = useRole(detailRef, redemptionRef, selfImportRef);
const showProgress = ref(false);
const progress = ref(0);
const type = ref(0); // 0 兑领中 1 添加中
let timer: any;
// 每隔3秒查询一次任务
function onStartQuery(fetchApi: (...args: any[]) => any, task_id: any) {
  showProgress.value = true;
  progress.value = 0;
  fetchApi().then(res => {
    if (res.code == 1000) {
      progress.value = Number(res.data.process ?? 100) ?? 100;
      if (res.data.status == "done") {
        showProgress.value = false;
        localStorage.removeItem("progressID");
        clearInterval(timer);
        onSearch();
      } else if (res.data.status == "error") {
        message("兑领失败", { type: "error" });
        showProgress.value = false;
        localStorage.removeItem("progressID");
        clearInterval(timer);
        onSearch();
      }
    }
  });
  timer = setInterval(() => {
    fetchApi()
      .then(res => {
        if (res.code == 1000) {
          progress.value = Number(res.data.process ?? 100) ?? 100;
          if (res.data.status == "done") {
            showProgress.value = false;
            localStorage.removeItem("progressID");
            clearInterval(timer);
            onSearch();
          } else if (res.data.status == "error") {
            message(`兑领status：${res.data.status}`, { type: "error" });
            showProgress.value = false;
            localStorage.removeItem("progressID");
            clearInterval(timer);
            onSearch();
          }
        }
      })
      .catch(err => {
        showProgress.value = false;
        clearInterval(timer);
      });
  }, 3000);
}
const onRefreshProgressWithOutbound = (e: any) => {
  onStartQuery(
    () =>
      customerData_taskDetail({
        logId: e
      }),
    e
  );
};

const onRefreshProgress = (e: any) => {
  onStartQuery(
    () =>
      exchange_taskDetail({
        logId: e
      }),
    e
  );
};
const onHighSeasProgress = (e:any) =>{
  onStartQuery(
    () =>
      customer_insea_progress({
        logId: e
      }),
    e
  );
}
onMounted(() => {
  // 判断刷新过后是否有进度id 如果没有即加载完成 还有则继续加载
  if (localStorage.getItem("progressID")) {
    let task_id = localStorage.getItem("progressID");
    if (type.value == 0) {
      // 兑领
      onRefreshProgress(task_id);
    } else {
      // 添加
      onRefreshProgressWithOutbound(task_id);
    }
  }
});
</script>

<template>
  <div class="main">
    <ABProgress
      v-model:show="showProgress"
      v-model:process="progress"
      v-model:type="type"
    ></ABProgress>
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item prop="keyword">
        <el-input
          v-model="form.keyword"
          placeholder="客户名称/企业名称"
          clearable
          class="w-[180px]!"
        />
      </el-form-item>
      <el-form-item prop="tag_id">
        <el-select
          v-model="form.tag_id"
          placeholder="客户标签"
          clearable
          class="w-[120px]!"
        >
          <el-option
            v-for="(item, index) in labelList"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="source_by">
        <el-select
          v-model="form.source_by"
          placeholder="数据来源"
          clearable
          class="w-[120px]!"
        >
          <el-option
            v-for="(item, index) in sourceList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入池时间" prop="entry_at">
        <el-date-picker
          v-model="form.entry_at"
          type="daterange"
          class="w-[240px]!"
          unlink-panels
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :shortcuts="shortcuts"
        />
      </el-form-item>
      <el-form-item prop="called_times">
        <el-input
          type="number"
          v-model="form.called_times"
          placeholder="群呼拨打次数"
          clearable
          class="w-[180px]!"
        />
      </el-form-item>
      <el-form-item v-if="permissions.is_cd_wl_table">
        <el-button
          type="primary"
          :icon="useRenderIcon('ri/search-line')"
          :loading="loading"
          @click="onSearch"
        >
          查询
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>

      <el-form-item>
        <el-dropdown
          v-if="permissions.is_cd_wl_add"
          style="margin-right: 12px"
          @command="handleCommand"
        >
          <el-button type="primary">
            补充数据<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                command="redemption"
                v-if="permissions.is_cd_wl_add_dl"
                @click="type = 0"
                >兑领</el-dropdown-item
              >
              <el-dropdown-item
                command="selfImport"
                v-if="permissions.is_cd_wl_add_zd"
                >自导入</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <!-- <el-button
          v-if="permissions.is_cd_wl_call"
          type="primary"
          :icon="Filter"
          @click="()=>{
            type = 1
            conditionsAllocateClick()
          }"
        >
          分配数据
        </el-button> -->
        <el-dropdown
          v-if="permissions.is_cd_wl_dispatch"
          style="margin-right: 12px"
        >
          <el-button type="primary">
            数据派发<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-if="permissions.is_cd_wl_dispatch"
                @click="conditionsAllocateClick()"
              >
                指定分配
              </el-dropdown-item>
              <el-dropdown-item
                @click="transferHighseasClick(onHighSeasProgress)"
                v-if="permissions.is_cd_wl_dispatch"
                >转至公海
                </el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button
          v-if="permissions.is_cd_wl_call "
          type="primary"
          :icon="useRenderIcon('ri:calculator-line')"
          @click="
            () => {
              type = 1;
              conditionsOutboundClick(onRefreshProgressWithOutbound);
            }
          "
        >
          按条件添加到外呼任务
        </el-button>
        <el-button
          v-if="permissions.is_cd_wl_tofq_condition"
          type="primary"
          :icon="useRenderIcon('ri:delete-bin-line')"
          @click="conditionsDiscardClick()"
        >
          按条件删除到废弃客池
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar
      title=""
      :columns="columns"
      @refresh="onSearch"
      :key="columns.length"
    >
      <template v-slot="{ size, dynamicColumns }">
        <!-- 多选显示 -->
        <div
          class="multipleInner"
          v-if="multipleSelection.length && permissions.is_cd_wl_tofq_batch"
        >
          <IconifyIconOffline
            :icon="Checkbox"
            style="color: #fff; width: 18px; height: 18px; cursor: pointer"
            @click="handleSelectionClear"
          />
          <b>已选中 {{ multipleSelection.length }} 项</b>

          <div class="multipHandle" @click="discardClick">
            <IconifyIconOffline :icon="DeleteBin" />
            <p>删除到废弃客池</p>
          </div>
        </div>
        <pure-table
          ref="tableRef"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="loading"
          :size="size"
          adaptive
          :adaptiveConfig="{ offsetBottom: 108 }"
          :data="dataList"
          :columns="dynamicColumns"
          :pagination="{ ...pagination, size }"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          @selection-change="handleSelectionChange"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(Eye)"
              @click="lookCustomer(row)"
            >
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <!-- 客户信息 -->
    <CustomerDetail
      ref="detailRef"
      :isBatch="permissions.is_cd_wl_tofq_batch"
      @onSearch="onSearch"
    ></CustomerDetail>

    <!-- 兑领 -->
    <Redemption
      ref="redemptionRef"
      @onSearch="onSearch"
      @refresh-progress="onRefreshProgress"
    ></Redemption>

    <!-- 自导入 -->
    <SelfImport
      ref="selfImportRef"
      @onSearch="onSearch"
      @onLabelChange="getLabelList"
    ></SelfImport>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 12px;
}

.multipleInner {
  background-color: var(--pure-theme-menu-active-before);
  height: 45px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  font-size: 14px;
  color: #ffffff;

  b {
    margin-left: 3px;
  }

  .multipHandle {
    padding: 5px 8px;
    margin-left: 30px;
    display: flex;
    align-items: start;
    cursor: pointer;
    border-radius: 5px;
    transition: all 0.1s;

    svg {
      font-size: 16px;
      color: #ffffff;
      margin-top: 2px;
    }

    p {
      margin-left: 5px;
    }

    &:hover {
      background-color: #ffffff;
      color: #000000;

      :deep(svg) {
        color: #000000;
      }
    }
  }
}

.main {
  margin: 12px 12px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
